<?php

namespace app\models\merchant;

use Yii;

/**
 * This is the model class for table "merchant_order".
 *
 * @property int $id
 * @property string $sn
 * @property int $merchant_id 商家ID
 * @property int $user_id 用户ID (支付用户)
 * @property float $total 应该支付总金额
 * @property float $money 支付现金
 * @property float $ticket 支付购物券
 * @property float $platform 平台需要支付多少
 * @property int $status 0 未支付, 1 已支付 2 代付给商家
 * @property string $create_time
 * @property string $update_time
 */
class MerchantOrder extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'merchant_order';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['sn'], 'required'],
            [['merchant_id', 'user_id', 'status'], 'integer'],
            [['total', 'money', 'ticket', 'platform'], 'number'],
            [['create_time', 'update_time'], 'safe'],
            [['sn'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'sn' => 'Sn',
            'merchant_id' => 'Merchant ID',
            'user_id' => 'User ID',
            'total' => 'Total',
            'money' => 'Money',
            'ticket' => 'Ticket',
            'platform' => 'Platform',
            'status' => 'Status',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
        ];
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    public static function generateSn()
    {
        do {
            $sn = date('YmdHis') . mt_rand(10000, 99999);
        } while(self::findOne(['sn' => $sn]));

        return $sn;
    }

    public function getMerchant()
    {
        return $this->hasOne(Merchant::class, ['id' => 'merchant_id']);
    }

    public function getPayFor()
    {
        return $this->hasOne(MerchantPayFor::class, ['pay_sn' => 'sn']);
    }
}
